package com.fm.parser.excel;

import com.fm.structure.base.Pair;

import java.util.ArrayList;
import java.util.List;

/**
 * @author finalmachine
 */
public abstract class AbstractExcelListHandler implements ExcelRowHandler {
    private static int getPosition(String columnName) {
        int i = 0;
        for (int j = 0; j < columnName.length(); j++) {
            i = i * 26 + (columnName.charAt(j) - 'A');
        }
        return i;
    }

    private static void add(List<Object> list, int position, Object val) {
        if (list.size() > position) {
            list.set(position, val);
        } else {
            for (int i = list.size(); i < position; i++) {
                list.add(null);
            }
            list.add(val);
        }
    }

    @Override
    public void doRow(int rowNum, List<Pair<String, Object>> cells) {
        List<Object> list = new ArrayList<>(cells.size());
        for(Pair<String, Object> cell : cells) {
            add(list, getPosition(cell.getLeft().replaceAll("\\d+$", "")), cell.getRight());
        }
        processRow(rowNum, list);
    }

    protected abstract void processRow(int rowNum, List<Object> cells);
}
